# -*- coding:utf-8 -*-

from rest_framework import serializers

from Apps.Demo.models.demo import Demo


# 自定义校验器，
"""
from rest_framework.validators import UniqueValidator, qs_exists

from apps.vadmin.utils.exceptions import APIException


class CustomUniqueValidator(UniqueValidator):

    # 继承,重写必填字段的验证器结果,防止字段暴露


    def __call__(self, value, serializer_field):
        # Determine the underlying model field name. This may not be the
        # same as the serializer field name if `source=<>` is set.
        field_name = serializer_field.source_attrs[-1]
        # Determine the existing instance, if this is an update operation.
        instance = getattr(serializer_field.parent, 'instance', None)

        queryset = self.queryset
        queryset = self.filter_queryset(value, queryset, field_name)
        queryset = self.exclude_current_instance(queryset, instance)
        if qs_exists(queryset):
            raise APIException(message=self.message)

    def __repr__(self):
        return super().__repr__()

"""


class demoSer(serializers.ModelSerializer):
    """
    # 可使用自定义校验器，也可定义error_messages
    username = serializers.CharField(required=True, max_length=150,
                                     validators=[
                                         CustomUniqueValidator(queryset=UserProfile.objects.all(), message="用戶已存在")],
                                     error_messages={
                                         "blank": "请输入用户名称",
                                         "required": "用户名称不能为空",
                                         "max_length": "用户名称过长",
                                     })

    # 时间格式转换，某个字段
    last_login = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)
    """
    class Meta:
        model = Demo
        fields = ["name", "age", "money"]


"""
# 读取字段
fields = ["name", "age", "money"]
# 排除字段
exclude = ('password', 'secret', 'user_permissions', 'groups', 'is_superuser', 'date_joined')
# 只读
read_only_fields = ('dept',)

"""

"""
# 新增数据时，格式转换
data['role'] = str(data['role']).split(',')
data['post'] = str(data['post']).split(',')
data['gender'] = {'男': '0', '女': '1', '未知': '2'}.get(data['gender'])
"""